package queue

import (
	"data-center/config"
	"errors"
)

// 定义错误
var (
	ErrQueueTypeNotSupported = errors.New("queue type not supported")
	ErrQueueNotFound         = errors.New("queue not found")
)

// Producer 消息生产者接口
type Producer interface {
	// Publish 发布消息到指定队列
	Publish(queueType string, message []byte) error
	// Close 关闭连接
	Close()
}

// Consumer 消息消费者接口
type Consumer interface {
	// Consume 消费消息
	Consume(timeout int) ([]byte, error)
	// Close 关闭连接
	Close()
}

// NewProducer 创建消息生产者
func NewProducer(cfg config.QueueConfig) (Producer, error) {
	switch cfg.Type {
	case "rabbitmq":
		if newRabbitMQProducer == nil {
			return nil, errors.New("RabbitMQ producer not registered")
		}
		return newRabbitMQProducer(cfg)
	case "kafka":
		if newKafkaProducer == nil {
			return nil, errors.New("Kafka producer not registered")
		}
		return newKafkaProducer(cfg)
	default:
		return nil, ErrQueueTypeNotSupported
	}
}

// NewConsumer 创建消息消费者
func NewConsumer(cfg config.QueueConfig, queueTypes []string) (Consumer, error) {
	switch cfg.Type {
	case "rabbitmq":
		return newRabbitMQConsumer(cfg, queueTypes)
	case "kafka":
		return newKafkaConsumer(cfg, queueTypes)
	default:
		return nil, ErrQueueTypeNotSupported
	}
}

// 内部工厂函数，由具体实现提供
var (
	newRabbitMQProducer func(cfg config.QueueConfig) (Producer, error)
	newRabbitMQConsumer func(cfg config.QueueConfig, queueTypes []string) (Consumer, error)
	newKafkaProducer    func(cfg config.QueueConfig) (Producer, error)
	newKafkaConsumer    func(cfg config.QueueConfig, queueTypes []string) (Consumer, error)
)

// RegisterRabbitMQProducer 注册RabbitMQ生产者工厂函数
func RegisterRabbitMQProducer(factory func(cfg config.QueueConfig) (Producer, error)) {
	newRabbitMQProducer = factory
}

// RegisterRabbitMQConsumer 注册RabbitMQ消费者工厂函数
func RegisterRabbitMQConsumer(factory func(cfg config.QueueConfig, queueTypes []string) (Consumer, error)) {
	newRabbitMQConsumer = factory
}

// RegisterKafkaProducer 注册Kafka生产者工厂函数
func RegisterKafkaProducer(factory func(cfg config.QueueConfig) (Producer, error)) {
	newKafkaProducer = factory
}

// RegisterKafkaConsumer 注册Kafka消费者工厂函数
func RegisterKafkaConsumer(factory func(cfg config.QueueConfig, queueTypes []string) (Consumer, error)) {
	newKafkaConsumer = factory
}
